package com.futvan.z.framework.util;

import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;
import com.futvan.z.system.zjob.z_job;
import com.futvan.z.system.zwarning.z_warning;

import java.util.HashMap;
import java.util.List;

/**
 * 预警监控工具类
 */
public class WarningUtil {

    /**
     * 根据预警ID获取预警记录
     * @param zid
     * @return
     */
    private static z_warning getWarningByid(String zid){
        z_warning w = null;
        if(z.isNotNull(zid)){
            w = z.getSqlSession().selectOne("z_warning_select_zid",zid);
        }
        return w;
    }

    /**
     * 启动预警
     * @param zids
     * @return
     */
    public static Result start_warning(String zids) throws Exception {
        Result result = new Result();
        if(z.isNotNull(zids)){
            String [] list = zids.split(",");
            for (String zid : list) {
                z_warning w = getWarningByid(zid);
                if(z.isNotNull(w)){
                    z_job warning_job = new z_job();
                    warning_job.setZid(w.getZid());
                    warning_job.setIsstart("1");//是否启用
                    warning_job.setJobtype("0");//任务类型
                    warning_job.setJobname("预警监控:"+w.getName());
                    warning_job.setJobclass("com.futvan.z.framework.core.WarningJob");
                    warning_job.setJobtime(w.getJobtime());
                    JobUtil.jobAdd(warning_job);

                    //变更状态
                    z.getSqlSession().update("update","update z_warning set is_run = '1' where zid = '"+w.getZid()+"'");
                }
            }
            result.setSuccess("启动预警成功：",list.length);
        }else{
            result.setError("start_warning:zids is null");
        }
        return result;
    }


    /**
     * 关闭预警
     * @param zids
     * @return
     */
    public static Result close_warning(String zids) throws Exception {
        Result result = new Result();
        if(z.isNotNull(zids)){
            String [] list = zids.split(",");
            for (String zid : list) {
                z_warning w = getWarningByid(zid);
                if(z.isNotNull(w)){
                    JobUtil.jobDelete(w.getZid());
                    //变更状态
                    z.getSqlSession().update("update","update z_warning set is_run = '0' where zid = '"+w.getZid()+"'");
                }
            }
            result.setSuccess("关闭预警成功：",list.length);
        }else{
            result.setError("close_warning:zids is null");
        }
        return result;
    }

    /**
     * 根据预警记录ID，发送预警信息
     * @param zid
     * @return
     */
    public static Result SendWarningMsg(String zid) throws Exception {
        Result result = new Result();
        if(z.isNotNull(zid)){
            z_warning warning = z.getSqlSession().selectOne("z_warning_select_zid",zid);
            if(z.isNotNull(warning)){
                if(z.isNull(warning.getUserid()) && z.isNull(warning.getRoleid())){
                    result.setError("SendWarningMsg：接收人与接收角色不能全为空");
                }else{
                    if(z.isNotNull(warning.getNotice_method())){
                        if(z.isNotNull(warning.getMsg())){
                            if(z.isNotNull(warning.getWarning_sql())){
                                //解析信息模板
                                String rmsg = MsgParse(warning.getWarning_sql(),warning.getMsg());
                                if(z.isNotNull(rmsg)){
                                    //获取发送方式
                                    String [] notice_method_array = warning.getNotice_method().split(",");
                                    for (String method : notice_method_array) {
                                        if("sms".equals(method)){
                                            //发送短信
                                            String tels = getWarningUserTelList(warning.getZid());
                                            HashMap<String,String> sms_map = new HashMap<String,String>();
                                            sms_map.put("msg",rmsg);
                                            Result sms_result = SmsUtil.Send(z.sp.get("warning_tel_template_code"),tels,sms_map);
                                            if(sms_result.ifError()){
                                                z.Exception("预警发送短信出错|"+sms_result.getMsg());
                                            }
                                        }else if("email".equals(method)){
                                            String emails = getWarningUserEmailList(warning.getZid());
                                            EmailUtil.sent(emails,"预警通知",rmsg);
                                        }
                                    }

                                    //更新最后执行时间
                                    z.getSqlSession().update("update","update z_warning set lasttime = now() where zid = '"+warning.getZid()+"'");
                                    result.setSuccess("执行"+warning.getName()+"|"+rmsg,null);
                                }else{
                                    result.setSuccess("执行"+warning.getName()+"|无信息需要通知",null);
                                }
                            }else{
                                result.setError("SendWarningMsg：SQL不可为空");
                            }
                        }else{
                            result.setError("SendWarningMsg：信息模板不可为空");
                        }

                    }else{
                        result.setError("SendWarningMsg：通知方式不可为空");
                    }
                }
            }else{
                result.setError("SendWarningMsg：zid无效");
            }
        }else{
            result.setError("SendWarningMsg：zid is null");
        }
        return result;
    }


    /**
     * 解析信息模板
     * @param warningSql
     * @param msg
     * @return
     */
    private static String MsgParse(String warningSql, String msg) {
        String rmsg = "";
        //获取SQL数据
        List<HashMap<String,String>> list = z.getSqlSession().selectList("select",warningSql);
        for (HashMap<String, String> info : list) {
            rmsg = rmsg + StringUtil.parseExpression(msg,info)+"\r\n";
        }
        return rmsg;
    }

    /**
     * 根据预警记录ID，获取接收人与角色手机号
     * @param zid
     * @return
     */
    private static String getWarningUserTelList(String zid) {
        StringBuffer tel_list_sql = new StringBuffer();
        tel_list_sql.append(" SELECT u.tel  ");
        tel_list_sql.append(" FROM z_warning c   ");
        tel_list_sql.append(" LEFT JOIN z_user u ON c.userid = u.zid  ");
        tel_list_sql.append(" where c.zid = '"+zid+"'  ");
        tel_list_sql.append(" UNION   ");
        tel_list_sql.append(" SELECT u.tel  ");
        tel_list_sql.append(" FROM z_warning c   ");
        tel_list_sql.append(" LEFT JOIN z_role_user ru ON c.roleid = ru.pid  ");
        tel_list_sql.append(" LEFT JOIN z_user u ON ru.userid = u.zid  ");
        tel_list_sql.append(" where c.zid = '"+zid+"'  ");
        List<String> tel_list = z.getSqlSession().selectList("selectone",tel_list_sql.toString());
        return StringUtil.ListToString(tel_list,",","","");
    }

    /**
     * 根据预警记录ID，获取接收人与角色Email
     * @param zid
     * @return
     */
    private static String getWarningUserEmailList(String zid) {
        StringBuffer email_list_sql = new StringBuffer();
        email_list_sql.append(" SELECT u.email  ");
        email_list_sql.append(" FROM z_warning c   ");
        email_list_sql.append(" LEFT JOIN z_user u ON c.userid = u.zid  ");
        email_list_sql.append(" where c.zid = '"+zid+"' AND u.email IS NOT NULL AND u.email != '' ");
        email_list_sql.append(" UNION   ");
        email_list_sql.append(" SELECT u.email  ");
        email_list_sql.append(" FROM z_warning c   ");
        email_list_sql.append(" LEFT JOIN z_role_user ru ON c.roleid = ru.pid  ");
        email_list_sql.append(" LEFT JOIN z_user u ON ru.userid = u.zid  ");
        email_list_sql.append(" where c.zid = '"+zid+"' AND u.email IS NOT NULL AND u.email != '' ");
        List<String> email_list = z.getSqlSession().selectList("selectone",email_list_sql.toString());
        return StringUtil.ListToString(email_list,",","","");
    }


}
